import express from "express"
const sqlite3 = require('sqlite3').verbose();
const dbname = './sqlite3.db';
// 创建并连接一个数据库
const db = new sqlite3.Database(dbname)

const router = express.Router()

function fail(data) {
    return {
        code: 1,
        data
    }
}

function ok(data) {
    return {
        code: 0,
        data
    }
}


router.get("/all", (req, res, next) => {
    try {
        db.all('SELECT * FROM codes', (err, rows) => {
            if (!err) {
                res.send(ok(rows))
                return
            }
            res.send(fail(err))
        })
    } catch (err) {
        res.send(fail(err))
    }
})


router.post("/save", (req, res, next) => {
    const body = req.body
    if (!body.content) {
        res.send(fail("content 不能为空"))
        return
    }
    if (!body.name) {
        res.send(fail("name 不能为空"))
        return
    }

    try {
        const sql = body.id ?
            `UPDATE codes SET content = $content, name = $name WHERE id = $id` :
            `INSERT INTO codes (content) VALUES ($content)`

        db.run(sql,
            {
                $content: body.content,
                $id: body.id || null,
                $name: body.name 
            },
            (err, rows) => {
                if (!err) {
                    res.send(ok(rows))
                    return
                }
                res.send(fail(err))
            })
    } catch (err) {
        res.send(fail(err))
    }
})

module.exports = router